#include "pickup.h"
#include "keysTest.h"

// ====================================================================================
// Pickup 皮卡遥控类实现
// ====================================================================================

Pickup::Pickup(Screen& screen, Keys& keys, NRF& nrf)
  : _screen(screen), _keys(keys), _nrf(nrf) {
}

void Pickup::main() {
  Serial.println("1.1 皮卡");

  // 初始化NRF通信
  initNRF();

  // 显示按键界面
  drawKeys(_screen, "皮卡");

  // 创建控制数据结构
  PickupKVS pickupData;

  // 主循环
  while (true) {
    // 更新按键显示
    updateKeys(_screen, _keys);

    // 更新控制数据
    updateControlData(pickupData);

    // 发送控制数据
    sendControlData(pickupData);

    // 延时
    delay(20);

    // 检查退出按键
    if (_keys.x.pressed()) {
      _screen.clearAndCenter();
      break;
    }
  }
}

void Pickup::initNRF() {
  const byte address[6] = ADDRESS_0;
  _nrf.radio.openWritingPipe(address);  // 发送端打开通信通道
  _nrf.radio.setPALevel(NRF_LEVEL);     // 设置通信功率
  _nrf.radio.stopListening();           // 停止监听，即设置为发送端
}

void Pickup::updateControlData(PickupKVS& kvs) {
  // 更新前端按键
  kvs.L_up = _keys.kvs.L_up;
  kvs.R_up = _keys.kvs.R_up;

  // 更新摇杆数据
  kvs.LX = _keys.kvs.LX;
  kvs.LY = _keys.kvs.LY;
  kvs.RX = _keys.kvs.RX;
  kvs.RY = _keys.kvs.RY;

  // 更新功能按键
  kvs.up = _keys.kvs.up;
  kvs.down = _keys.kvs.down;
  kvs.left = _keys.kvs.left;
  kvs.right = _keys.kvs.right;
  kvs.o = _keys.kvs.o;
  kvs.x = _keys.kvs.x;
  kvs.a = _keys.kvs.a;
  kvs.b = _keys.kvs.b;

  // 更新拨杆开关
  kvs.sw_L1 = _keys.kvs.switch_L1;
  kvs.sw_L2 = _keys.kvs.switch_L2;
  kvs.sw_R1 = _keys.kvs.switch_R1;
  kvs.sw_R2 = _keys.kvs.switch_R2;

  // 更新电位器旋钮
  kvs.L_knob = _keys.kvs.L_knob;
  kvs.R_knob = _keys.kvs.R_knob;
}

void Pickup::sendControlData(const PickupKVS& kvs) {
  // 一次最多可以传输32个字节
  _nrf.radio.write(&kvs, sizeof(kvs));
}
